{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "8c673aa0",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-12-28 18:54:20.749653: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2 FMA\n",
      "To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.\n"
     ]
    }
   ],
   "source": [
    "from tensorflow import keras\n",
    "keras.__version__\n",
    "import os, shutil"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "7ec629bb",
   "metadata": {},
   "outputs": [],
   "source": [
    "#change working directory\n",
    "os.chdir('/Users/manueldominguez/Desktop/DS1')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "6086473c",
   "metadata": {},
   "outputs": [],
   "source": [
    "from keras.preprocessing import image\n",
    "import keras.backend as K\n",
    "import numpy as np\n",
    "#import cv2\n",
    "import sys"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9c614e85",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e9be7e54",
   "metadata": {},
   "outputs": [],
   "source": [
    "#FOR DATASET 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "3da7ed8c",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-12-28 18:54:45.602950: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2 FMA\n",
      "To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.\n"
     ]
    }
   ],
   "source": [
    "#load model:\n",
    "from keras.models import model_from_json\n",
    "# cargar json y crear el modelo\n",
    "json_file = open('resnet.json', 'r')\n",
    "loaded_model_json = json_file.read()\n",
    "json_file.close()\n",
    "model = model_from_json(loaded_model_json)#change sequentially\n",
    "# cargar pesos al nuevo modelo\n",
    "model.load_weights(\"resnet.h5\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "ee9ca6a6",
   "metadata": {},
   "outputs": [],
   "source": [
    "#load testing directory\n",
    "test_dir= '/Users/manueldominguez/Desktop/DS1_testing'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "5189a184",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found 85 images belonging to 2 classes.\n"
     ]
    }
   ],
   "source": [
    "from tensorflow.keras.preprocessing.image import ImageDataGenerator\n",
    "from tensorflow.keras.applications.resnet50 import preprocess_input #for RESNET 50\n",
    "\n",
    "# Note that the validation data should not be augmented!\n",
    "test_datagen = ImageDataGenerator(preprocessing_function= \\\n",
    "    keras.applications.resnet50.preprocess_input)#OJO!!!\n",
    "\n",
    "test_generator = test_datagen.flow_from_directory(\n",
    "        test_dir,\n",
    "        target_size=(80, 400),\n",
    "        batch_size=32,\n",
    "        class_mode='categorical',\n",
    "        shuffle=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "14fdb43a",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/var/folders/dk/_8vzqxyx5xz3z7892hyzpgxw0000gn/T/ipykernel_40396/3983181610.py:1: UserWarning: `Model.predict_generator` is deprecated and will be removed in a future version. Please use `Model.predict`, which supports generators.\n",
      "  predictions=model.predict_generator(test_generator, steps=len(test_generator), verbose=1)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3/3 [==============================] - 9s 3s/step\n"
     ]
    }
   ],
   "source": [
    "predictions=model.predict_generator(test_generator, steps=len(test_generator), verbose=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "08e0bae0",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "val_preds = np.round(predictions)# from probabilities to 0 or 1\n",
    "val_trues = test_generator.classes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "28b60571",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/var/folders/dk/_8vzqxyx5xz3z7892hyzpgxw0000gn/T/ipykernel_40396/2737452301.py:7: UserWarning: `Model.predict_generator` is deprecated and will be removed in a future version. Please use `Model.predict`, which supports generators.\n",
      "  Y_pred = model.predict_generator(test_generator, num_of_test_samples // batch_size+1)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Confusion Matrix\n",
      "[[17  3]\n",
      " [ 4 61]]\n"
     ]
    }
   ],
   "source": [
    "#modify:\n",
    "from sklearn.metrics import confusion_matrix\n",
    "from sklearn.metrics import classification_report\n",
    "import numpy as np\n",
    "num_of_test_samples = 85 #number of testing samples\n",
    "batch_size=32 #batch size for the validation set\n",
    "Y_pred = model.predict_generator(test_generator, num_of_test_samples // batch_size+1)\n",
    "y_pred = np.argmax(Y_pred, axis=1)\n",
    "print('Confusion Matrix')\n",
    "print(confusion_matrix(test_generator.classes, y_pred))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "2a844b45",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Classification Report\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "        Croc       0.81      0.85      0.83        20\n",
      "          cm       0.95      0.94      0.95        65\n",
      "\n",
      "    accuracy                           0.92        85\n",
      "   macro avg       0.88      0.89      0.89        85\n",
      "weighted avg       0.92      0.92      0.92        85\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print('Classification Report')\n",
    "target_names = ['Croc', 'cm']\n",
    "print(classification_report(test_generator.classes, y_pred, target_names=target_names))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "01313ab2",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "52affb75",
   "metadata": {},
   "outputs": [],
   "source": [
    "#FOR DATASET 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "30647967",
   "metadata": {},
   "outputs": [],
   "source": [
    "#change working directory\n",
    "os.chdir('/Users/manueldominguez/Desktop/DS2')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "f81f74be",
   "metadata": {},
   "outputs": [],
   "source": [
    "#LOAD MODEL:\n",
    "from keras.models import model_from_json\n",
    "# cargar json y crear el modelo\n",
    "json_file = open('vgg16-definitivo25.json', 'r')\n",
    "loaded_model_json = json_file.read()\n",
    "json_file.close()\n",
    "model = model_from_json(loaded_model_json)#change sequentially\n",
    "# cargar pesos al nuevo modelo\n",
    "model.load_weights(\"vgg16-definitivo25.h5\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1f771d7f",
   "metadata": {},
   "outputs": [],
   "source": [
    "#IF AN ERROR SHOWED UP WHILE TRYING TO UPLOAD THE MODEL WITH THE PREVIOUS CODE, USE THIS:\n",
    "\n",
    "import tensorflow as tf\n",
    "from tensorflow.keras.utils import get_custom_objects\n",
    "from keras.layers import Activation\n",
    "from keras.models import model_from_json\n",
    "\n",
    "# Define Swish activation function\n",
    "def swish(x, **kwargs):\n",
    "    return x * tf.keras.backend.sigmoid(x)\n",
    "\n",
    "# Register Swish activation globally\n",
    "get_custom_objects().update({'swish': swish})\n",
    "\n",
    "# Load model architecture from JSON\n",
    "with open(\"vgg16-definitivo25.json\", \"r\") as json_file:\n",
    "    loaded_model_json = json_file.read()\n",
    "\n",
    "# Load model with custom objects, including Activation layer\n",
    "model = model_from_json(\n",
    "    loaded_model_json,\n",
    "    custom_objects={\n",
    "        'swish': swish,\n",
    "        'Activation': Activation,  # Explicitly register Activation layer\n",
    "    }\n",
    ")\n",
    "\n",
    "# Load model weights\n",
    "model.load_weights(\"vgg16-definitivo25.h5\")\n",
    "print(\"Model with Swish activation loaded successfully!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "7076b9f3",
   "metadata": {},
   "outputs": [],
   "source": [
    "#load testing directory\n",
    "test_dir= '/Users/manueldominguez/Desktop/DS2/DS2_testing'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a2e9d093",
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensorflow.keras.preprocessing.image import ImageDataGenerator\n",
    "from tensorflow.keras.applications.vgg16 import preprocess_input #for RESNET 50\n",
    "\n",
    "# Note that the validation data should not be augmented!\n",
    "test_datagen = ImageDataGenerator(preprocessing_function= \\\n",
    "    keras.applications.vgg16.preprocess_input)#OJO!!!\n",
    "\n",
    "test_generator = test_datagen.flow_from_directory(\n",
    "        test_dir,\n",
    "        target_size=(80, 400),\n",
    "        batch_size=32,\n",
    "        class_mode='categorical',\n",
    "        shuffle=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "75216099",
   "metadata": {},
   "outputs": [],
   "source": [
    "predictions=model.predict_generator(test_generator, steps=len(test_generator), verbose=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "107c8c39",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "val_preds = np.round(predictions)# from probabilities to 0 or 1\n",
    "val_trues = test_generator.classes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3ea591be",
   "metadata": {},
   "outputs": [],
   "source": [
    "#modify:\n",
    "from sklearn.metrics import confusion_matrix\n",
    "from sklearn.metrics import classification_report\n",
    "import numpy as np\n",
    "num_of_test_samples = 119 #number of testing samples\n",
    "batch_size=32 #batch size for the validation set\n",
    "Y_pred = model.predict_generator(test_generator, num_of_test_samples // batch_size+1)\n",
    "y_pred = np.argmax(Y_pred, axis=1)\n",
    "print('Confusion Matrix')\n",
    "print(confusion_matrix(test_generator.classes, y_pred))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dd83a35d",
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Classification Report')\n",
    "target_names = ['tm', 'cm', 'tramp']\n",
    "print(classification_report(test_generator.classes, y_pred, target_names=target_names))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d23db011",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "23fcb90d",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
